package ejb.contentManagement;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import ejb.dto.FlightDTO;
import entities.Airport;
import entities.Flight;
import entities.Location;
import entities.Period;

@Stateless
public class FlightBean implements FlightMgr {
	
	@PersistenceContext
    private EntityManager em;
	
	/**
	 * Retrieve entity Flight from the associated Id
	 * @param id
	 * @return entity Flight associated to the <code>id</code>
	 */
	public Flight getFlight(int id) {
		return em.find(Flight.class, id);
	}
	
	/**
	 * Retrieve all Flight entities
	 * @return all Flight entities
	 */
	public List<Flight> getAllFlights() {
    	return em.createNamedQuery("Flight.findAll", Flight.class)
                .getResultList();
    }
	
	/**
	 * Retrieve entity Flight from the associated Id and convert it to corresponding FlightDTO
	 */
	@Override
	public FlightDTO getFlightDTO(int id) {
		return  convertToDTO(getFlight(id));
    }
	
	/**
	 * Retrieve all Flight entities and convert them into corresponding list of FlightDTO
	 */
	@Override
	public List<FlightDTO> getAllFlightsDTO() {
		List<Flight> list = getAllFlights();
		List<FlightDTO> newList = new ArrayList<FlightDTO>();
		for(Flight obj : list) {
			newList.add(convertToDTO(obj));
		}
		return newList;
	}
	
	/**
	 * Retrieve depart Flight entities corresponding to specified Location and Period, and convert them 
	 * into corresponding list of FlightDTO only if they have available seats
	 */
	@Override
	public List<FlightDTO> getAllDepFlightsByLocation(int locationId, int periodId){
		Location location = em.find(Location.class, locationId);
		Period period = em.find(Period.class, periodId);
		FlightDTO toAdd = null;
		List<Flight> list = em.createNamedQuery("Flight.findFlightsToInPeriod", Flight.class).setParameter("a", location.getAirports()).setParameter("s", period.getFromDate()).setParameter("e", period.getToDate()).getResultList(); 
		List<FlightDTO> newList = new ArrayList<FlightDTO>();
		for(Flight f : list) {
			if(f.getRemaining()>0) {
				toAdd = FlightBean.convertToDTO(f);
				newList.add(toAdd);
			}
		}

		return newList;
	}
	
	/**
	 * Retrieve landing Flight entities corresponding to specified Location and Period, and convert them 
	 * into corresponding list of FlightDTO only if they have available seats
	 */
	@Override
	public List<FlightDTO> getAllRetFlightsByLocation(int locationId, int periodId){
		Location location = em.find(Location.class, locationId);
		Period period = em.find(Period.class, periodId);
		FlightDTO toAdd = null;
		List<Flight> list = em.createNamedQuery("Flight.findFlightsFromInPeriod", Flight.class).setParameter("a", location.getAirports()).setParameter("s", period.getFromDate()).setParameter("e", period.getToDate()).getResultList(); 
		List<FlightDTO> newList = new ArrayList<FlightDTO>();
		for(Flight f : list) {
			if(f.getRemaining()>0) {
				toAdd = FlightBean.convertToDTO(f);
				newList.add(toAdd);
			}
		}
		return newList;
	}
	
	/**
	 * Convert entity Flight (parameter <code>f</code>) into corresponding FlightDTO 
	 * @param f
	 * @return converted FlightDTO
	 */
	public static FlightDTO convertToDTO(Flight f) {
		if(f == null){
			return null;
		}
		FlightDTO dto = new FlightDTO();
		
		dto.setId(f.getId());
		dto.setCompany(f.getCompany());
		dto.setLandingTime(f.getLandingTime());
		dto.setDepartureTime(f.getDepartureTime());
		dto.setAirport1(AirportBean.convertToDTO(f.getAirport1()));
		dto.setAirport2(AirportBean.convertToDTO(f.getAirport2()));
		dto.setPrice(f.getPrice());
		dto.setRemaining(f.getRemaining());
		return dto;
	}
	
	/**
	 * Retrieve entity Flight from the associated Id and delete the corresponding element from the database
	 */
	@Override
	@RolesAllowed({"ADMINS"})
	public boolean deleteFlight(int id) {
		try{
			em.remove(em.find(Flight.class, id));
			em.flush();
		}
		//Catch exceptions in the delete operation from database
		catch(Exception e){
			return false;
		}
		return true;
	}
	
	/**
	 * Create entity Flight from corresponding FlightDTO and update corresponding element in database
	 */
	@Override
	@RolesAllowed({"ADMINS"})
	public boolean updateFlight(FlightDTO updatedFlight) {
		if(updatedFlight.getCompany().equals("") || 
			updatedFlight.getCompany().startsWith(" ") || 
			updatedFlight.getCompany()==null || 
			updatedFlight.getDepartureTime().after(updatedFlight.getLandingTime()) || 
			updatedFlight.getAirport1Id()==updatedFlight.getAirport2Id() ||
			updatedFlight.getPrice() < 0 ||
			updatedFlight.getPrice() > 50000 ||
			updatedFlight.getRemaining() < 0 ||
			updatedFlight.getRemaining() > 1000)
			return false;
		try{
			em.merge(new Flight(updatedFlight, em.find(Airport.class, updatedFlight.getAirport1Id()), em.find(Airport.class, updatedFlight.getAirport2Id())));
			em.flush();
		}
		//catch exceptions in the update operation of database
		catch(Exception e){
			return false;
		}
		return true;
	}
	
	/**
	 * Create entity Flight from corresponding FlightDTO and insert new corresponding element in database
	 */
	@Override
	@RolesAllowed({"ADMINS"})
	public boolean insertFlight(FlightDTO newFlight) {
		if(newFlight.getCompany().equals("") ||
			newFlight.getCompany().startsWith(" ") || 
			newFlight.getCompany()==null || 
			newFlight.getDepartureTime().after(newFlight.getLandingTime()) || 
			newFlight.getAirport1Id()==newFlight.getAirport2Id() ||
			newFlight.getPrice() < 0 ||
			newFlight.getPrice() > 50000 ||
			newFlight.getRemaining() < 0 ||
			newFlight.getRemaining() > 1000)
			return false;
		try{
			em.persist(new Flight(newFlight, em.find(Airport.class, newFlight.getAirport1Id()), em.find(Airport.class, newFlight.getAirport2Id())));
			em.flush();
		}
		//Catch exceptions in the insert operation in database
		catch(Exception e){
			return false;
		}
		return true;
	}
	
	
}
